package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.Classes;
import com.bnz.pojo.R;
import com.bnz.service.ClassesService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/classes")
public class ClassesServlet extends HttpServlet {
    private ClassesService classesService;
    @Override
    public void init() throws ServletException {
        // 得到spring容器
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        // 从spring容器中得到javaBean
        classesService = wac.getBean(ClassesService.class);
    }

    // 1. 查询所有班级
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.1 处理页面响应
        resp.setContentType("text/html;charset=UTF8");
        // 1.2 查询所有班级
        List<Classes> classes = classesService.findAll();
        // 1.3 将集合转换为R对象
        R r = R.ok().put("list", classes);
        // 1.4 输出
        resp.getWriter().println(JSON.toJSONString(r));
        // 1.5 刷新
        resp.getWriter().flush();
    }
}
